package threadTest.synchronizedTest.oddEven;

/**
 * 功能描述:奇数偶数
 * 2024/08/29
 *
 * @author ZhangYi
 */
public class OddEven {
	/**
	 * num : 初始值
	 */
	private int num;
	/**
	 * max num : 最大值
	 */
	private int maxNum;

	public OddEven(int num) {
		this.num = 1;
		this.maxNum = num;
	}

	/**
	 * 打印奇数
	 *
	 * @author ZhangYi
	 */
	public synchronized void printEven() throws InterruptedException {
		if (num >= maxNum) {
			return;
		}
		if (num % 2 != 0) {
			this.wait();
		}
		System.out.println(Thread.currentThread().getName() + " => " + num);
		num++;
		this.notifyAll();
	}

	/**
	 * 打印偶数
	 *
	 * @author ZhangYi
	 */
	public synchronized void printOdd() throws InterruptedException {
		if (num >= maxNum) {
			return;
		}
		if (num % 2 != 1) {
			this.wait();
		}
		System.out.println(Thread.currentThread().getName() + " => " + num);
		num++;
		this.notifyAll();
	}
}
